package service

import (
	"context"
	"github.com/rs/xid"
	"gitee.com/man0sions/go-cron/common"
	"log"
	"strconv"

	"net"
	"net/http"
	"time"
)

type Api struct {
	Server *http.Server
}

var (
	GApi *Api
)

func actionBefore(mux http.Handler) http.Handler {
	var (
		err      error
		hashid   xid.ID
		testDate time.Time
	)
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		hashid = xid.New()
		lc, _ := time.LoadLocation("Asia/Shanghai")
		if testDate, err = time.ParseInLocation("20060102", r.FormValue("test_date"), lc); err != nil {
			testDate = time.Now()
		}
		r = r.WithContext(context.WithValue(r.Context(), common.TEST_DATE, testDate))
		r = r.WithContext(context.WithValue(r.Context(), common.LOGID, hashid.String()))
		mux.ServeHTTP(w, r)
	})
}
func InitApi(HandleMap map[string]http.HandlerFunc) (err error) {
	var (
		mux          *http.ServeMux
		httpServer   *http.Server
		ln           net.Listener
		staticHandle http.Handler
	)

	mux = http.NewServeMux()
	for k, v := range HandleMap {
		mux.Handle(k, v)
	}
	staticHandle = http.FileServer(http.Dir(common.GConfig.Viper.GetString("Webroot")))
	mux.Handle("/", http.StripPrefix("/", staticHandle))

	if ln, err = net.Listen("tcp", ":"+strconv.Itoa(common.GConfig.Viper.GetInt("ApiPort"))); err != nil {
		return
	}

	httpServer = &http.Server{
		Handler:      actionBefore(mux),
		ReadTimeout:  time.Duration(common.GConfig.Viper.GetInt("ApiReadTimeout")) * time.Millisecond,
		WriteTimeout: time.Duration(common.GConfig.Viper.GetInt("ApiWriteTimeout")) * time.Millisecond,
	}
	GApi = &Api{
		Server: httpServer,
	}
	log.Println("listen on ",common.GConfig.Viper.GetInt("ApiPort"))
	go httpServer.Serve(ln)
	return
}
